package com.huaxiafinance.management.util;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by lenovo on 2017/5/24.
 */

public class QiNiuUtil
{
    private static final Logger log = Logger.getLogger(QiNiuUtil.class);

    private static String ak = PropertiesLoader.getProperty("qiniu.accesskey");

    private static String sk = PropertiesLoader.getProperty("qiniu.secretkey");

    private static Auth auth = Auth.create(ak, sk);

    private static String bucket = PropertiesLoader.getProperty("qiniu.bucket");

    private static String domain = PropertiesLoader.getProperty("qiniu.domain");

    private static String getUpToken()
    {
        return auth.uploadToken(bucket, null, 3600, new StringMap().put("insertOnly", 1));
    }

    /**
     * 返回图片唯一标识key
     *
     * @param file64
     * @return String
     */
    public static String setFile64(String file64)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String dateFormat = sdf.format(new Date());
        String name = "images/" + dateFormat + "/" + UUIDUtil.getUUID();
        String url = "http://upload-z2.qiniu.com" + "/putb64/-1/key/"
                     + UrlSafeBase64.encodeToString(name);
        // 非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().url(url).addHeader("Content-Type",
            "application/octet-stream").addHeader("Authorization", "UpToken " + getUpToken()).post(
                rb).build();
        OkHttpClient client = new OkHttpClient();
        Response response = null;
        try
        {
            response = client.newCall(request).execute();
            log.info("图片上传回应" + response);
        }
        catch (IOException e)
        {
            log.error("图片上传异常", e);
        }
        finally
        {
            if (response != null)
            {
                response.close();
            }
        }
        return name;
    }

    /**
     * 根据key删图片
     *
     * @param key
     * @return boolean
     */
    public static boolean deleteFile(String key)
    {
        String enc = UrlSafeBase64.encodeToString(bucket + ":" + key);
        String url = "http://rs.qiniu.com" + "/delete/" + enc;
        String token = auth.sign("/delete/" + enc + "\n");

        Request request = new Request.Builder().url(url).addHeader("Content-Type",
            "x-www-form-urlencoded")// x-www-form-urlencoded
            .addHeader("Authorization", "QBox " + token)//
            .build();
        OkHttpClient client = new OkHttpClient();
        Response response = null;
        try
        {
            response = client.newCall(request).execute();
        }
        catch (IOException e)
        {
            log.error("错误++++++" + e);
        }
        if (response != null)
        {
            if (612 == response.code() || 200 == response.code())
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 获得全路径
     *
     * @param base64
     * @return String
     */
    public static String url(String base64)
    {
        String key = setFile64(base64);
        return domain + "/" + key;
    }

    /**
     * 获得路径
     *
     * @param file
     * @return String
     * @throws Exception
     */
    public static String getUrl(MultipartFile file)
        throws Exception
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String dateFormat = sdf.format(new Date());
        String name = "images/" + dateFormat + "/" + UUIDUtil.getUUID();
        Configuration cfg = new Configuration(Zone.zone2());
        // ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        try
        {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            String upToken = getUpToken();
            try
            {
                com.qiniu.http.Response response = uploadManager.put(byteInputStream, name,
                    upToken, null, null);
                // 解析上传成功的结果
                new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            }
            catch (QiniuException ex)
            {
                log.error("错误++++++" + ex);
                com.qiniu.http.Response r = ex.response;
                try
                {
                    System.err.println(r.bodyString());
                }
                catch (QiniuException ex2)
                {
                    log.error("错误++++++" + ex2);
                }
            }
        }
        catch (UnsupportedEncodingException ex)
        {
            log.error("错误++++++" + ex);
        }
        log.info(domain + "/" + name);
        return domain + "/" + name;
    }

    /**
     * 获取文件base64
     *
     * @param key
     * @return String
     */
    public static String getBase64Stream(String key)
    {
        try
        {
            String url = getUrl1(key);

            return getImageStrFromUrl(url);
        }
        catch (Exception e)
        {
            log.error("从七牛云上获取图片Base64出错 key值为:::" + key);
            return null;
        }
    }

    /**
     * @param imgURL
     *            网络资源位置
     * @return String Base64字符串
     * @Title: GetImageStrFromUrl
     * @Description: TODO(将一张网络图片转化成Base64字符串)
     */
    public static String getImageStrFromUrl(String imgURL)
    {
        byte[] data = null;
        try
        {
            // 创建URL
            URL url = new URL(imgURL);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(1 * 1000000000);
            InputStream inStream = conn.getInputStream();
            int count = 990000;
            data = new byte[count];
            int readCount = 0; // 已经成功读取的字节的个数
            for (int i = 0; i < 20; i++ )
            {
                try
                {
                    Thread.sleep(400);
                }
                catch (InterruptedException e)
                {
                    log.error("错误++++++" + e);
                    Thread.currentThread().interrupt();
                }
                readCount += inStream.read(data, readCount, count - readCount);
            }
            inStream.close();
        }
        catch (IOException e)
        {
            log.error("错误++++++" + e);
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    public static String getUrl1(String key)
    {
        Long e = System.currentTimeMillis() / 1000 + 3600000;
        String url = "http://ooypfzh2f.bkt.clouddn.com" + "/" + key + "?e=" + e;
        String token = auth.sign(url);
        url += "&token=" + token;
        return url;
    }
}
